var organTreeSearch_keydown=0;
$(function(){
	//滚动条
	$(".nicescroll").niceScroll({
		touchbehavior:false
		,cursorcolor:"#ccc"
		,cursoropacitymax:1
		,cursorwidth:7
		,cursorborder:"0"
		,cursorborderradius:"10px"
		,background:"none"
		,autohidemode:"scroll"
	});
	
	//左侧菜单点击事件
	$(".menu").click(function(){
		if($(this).next(".menu_sub").length==1){
			$(".menu_sub").hide();
			$(this).next(".menu_sub").toggle();
		}
	});
	
	//选择项
	
	$(document).on("click",".checkitem",function(){
		if($(this).hasClass("active")){
			//如果只有一个，则不取消
			if($(this).siblings(".active").length!=0){
				$(this).removeClass("active");
			}
		}else{
			if($(this).parent().hasClass("onlyone")){
				$(this).addClass("active").siblings().removeClass("active");
			}else{
				$(this).addClass("active");
			}
		}
	});
	
	
	$.fn.extend({ 
		validateWrapper:function(options){
			if(options == undefined){
				options = {};
			}
			var that = this;
			var opts;
			if(typeof(formRule) != "undefined"){
				opts = $.extend(true, formRule, options);
				if(opts.rules){
					$.each(opts.rules, function(a,b){
						delete opts["rules"][a]["name"];
					});
				}
			}else{
				opts = options;
			}
			$(this).validate(opts);
		}
	});
	
	$.dictJs = function(dictName, value){
		if (value == '')
			return '';
		try {
			var _data = eval("dictJs_" + dictName + "['" +value+ "']");
			if (_data == undefined) {
				return value;
			} else {
				return _data.name;
			}
		} catch (e) {
			console.log("js 字典项转换出错. dictName:"+dictName + ", value:" + value);
		}
	}
	
	//tab
	$(".tabtitle .item").click(function(){
		$(this).addClass("active").siblings().removeClass("active");
		var _index=$(this).parent().children().index($(this));
		var _obj=$(this).parent().siblings(".tabcontent").eq(_index).addClass("active").siblings().removeClass("active");
	});
	
	
	$(document).on("keyup",".organTreeSearch",function(){//修改成这样的写法
	   	organTreeSearch_keydown=organTreeSearch_keydown+1;
	   	var treeid=$(this).attr("treeid");
		window.setTimeout("searchOrganTree("+organTreeSearch_keydown+",'"+treeid+"','"+$(this).val()+"')",300);
		//显示所有
		var treeobj=$.fn.zTree.getZTreeObj(treeid);
		var hidenodes =treeobj.getNodesByParam("isHidden", true);
    	treeobj.showNodes(hidenodes);
	});
	
});

/***加载组织机构弹出框***/

var organDialogTreetreeSetting = {
    view: {
        showLine: true
    },
    check: {
			enable: true,
			chkboxType:{ "Y" : "", "N" : "ps" },
			chkboxType:{ "Y" : "", "N" : "" }
	},
    data: {
        simpleData: {
            enable: true
        }
    }
};

function organTreeWindow(callback,config,params){
	dialog({
		id:"id-alert-treewindow",
		title:"选择党组织:",
		width:400,
		height:450,
		padding:0,
		fixed:true,
		quickClose: true,
    	content:'<div style="height:390px;overflow:auto" id="organDialogTree"><div class="orgdialogtreeinputbox"><input treeid="organDialogTree_ul" type="text" class="orgdialogtreeinput organTreeSearch" placeholder="请输入党组织拼音首字母或中文名称搜索"/></div><ul id="organDialogTree_ul" class="ztree"></ul></div>',
    	cancelValue: '取  消',
    	okValue: '确  认',
    	ok: function () {
    		//获取选择的对象
    		if(organDialogTreetreeSetting.check.enable){
    			var nodes = organDialogTree.getCheckedNodes(true);
    			callback(nodes);
    		}else{
    			var nodes = organDialogTree.getSelectedNodes();
    			callback(nodes);
    		}
    	}
	}).showModal();
	
	//判断是否需要加载数据，如果已经加载过了，就不需要重新加载了
	loadorganDialogTree(params,config);
}

function loadorganDialogTree(params,config){
$.ajax({
    type: "post",
    url: base + "/admin/partyOrgan/orgTreeJson",
    dataType: "json",
    data:params,
    success: function (result) {
    	_organDialogTreeIsLoading=true;
        var nodes = new Array();
        for (var i = 0; i < result.data.length; i++) {
            var _organ = result.data[i];
            var _obj = {
                id:_organ.code,
                pId:_organ.autoParentCode,
                code: _organ.code,
                organId:_organ.id,
                name: _organ.organName,
                name2:_organ.organName+"-"+_organ.organNamePinyin,
                orgType:_organ.organType,
                icon:_organ.depth==1?base + "/static/res/mng/img/dh.png":base + "/static/res/mng/img/treeicon.png",
                open:_organ.depth==1?true:false
            };
            nodes.push(_obj);
        }
        if(config){
        	$.extend(organDialogTreetreeSetting, config);
        }
        organDialogTree = $.fn.zTree.init($("#organDialogTree_ul"), organDialogTreetreeSetting, nodes);
    }
});
}


var checkmap = {};
function searchOrganTree(keyDownTimes,treeid,keys){
	if(organTreeSearch_keydown!=keyDownTimes){
		return;
	}
	/**
	 * 获取输入关键字
	 */
	var key = keys.toLowerCase().replace(/(^\s*)|(\s*$)/g,"");
	/**
	 * 获取查询的节点list
	 */
	var organTree = $.fn.zTree.getZTreeObj(treeid);
	var nodeList = organTree.getNodesByParamFuzzy("name2", key);
	getAllparent(nodeList,keyDownTimes);
	checkAllnodes(organTree);
}
/**
 * 找出某个节点的所有上级节点
 */
function getAllparent(nodes){
	checkmap = {};
	for(var i=0;i<nodes.length;i++){
		getParent(nodes[i]);
		checkmap[nodes[i].id]=1;
	}
}

function getParent(nod){
	var _p=nod.getParentNode();
	if(_p){
		getParent(_p);
		checkmap[_p.id]=1;
	}
}
function checkAllnodes(trees) {
	//选中所有二级节点
    var level3List = trees.getNodesByParam("level", "3");
    for (var i = 0; i < level3List.length; i++) {
        //判断二级节点是否在范围内
        var _thisObj = checkmap[level3List[i].id];
        if (!_thisObj) {
            trees.hideNode(level3List[i]);//隐藏
        }
    }
    //选中所有二级节点
    var level2List = trees.getNodesByParam("level", "2");
    for (var i = 0; i < level2List.length; i++) {
        //判断二级节点是否在范围内
        var _thisObj = checkmap[level2List[i].id];
        if (!_thisObj) {
            trees.hideNode(level2List[i]);//隐藏
        }
    }
	//处理一级
    var level1List = trees.getNodesByParam("level", "1");
    for (var i = 0; i < level1List.length; i++) {
        //判断是否存在下级，如果不存在下级，则是需要隐藏
        var _thisObj = checkmap[level1List[i].id];
        if (!_thisObj) {
            //隐藏
            trees.hideNode(level1List[i]);
        }
    }
}


function dateFormat(date, format){ 
	/**
	 * //使用方法 
		var now = new Date(); 
		var nowStr = now.format("yyyy-MM-dd hh:mm:ss"); 
		//使用方法2: 
		var testDate = new Date(); 
		var testStr = testDate.format("YYYY年MM月dd日hh小时mm分ss秒"); 
		alert(testStr); 
		//示例： 
		alert(new Date().Format("yyyy年MM月dd日")); 
		alert(new Date().Format("MM/dd/yyyy")); 
		alert(new Date().Format("yyyyMMdd")); 
		alert(new Date().Format("yyyy-MM-dd hh:mm:ss"));
	 */
	var o = { 
	"M+" : date.getMonth()+1, //month 
	"d+" : date.getDate(), //day 
	"h+" : date.getHours(), //hour 
	"m+" : date.getMinutes(), //minute 
	"s+" : date.getSeconds(), //second 
	"q+" : Math.floor((date.getMonth()+3)/3), //quarter 
	"S" : date.getMilliseconds() //millisecond 
	} ;

	if(/(y+)/.test(format)) { 
		format = format.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length)); 
	} 

	for(var k in o) { 
		if(new RegExp("("+ k +")").test(format)) { 
			format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length)); 
		} 
	} 
	return format; 
}